#include "AvatarLabel.h"

AvatarLabel::AvatarLabel(QWidget *parent, const QPixmap &avatar)
    : QLabel{parent},
      m_pixmap{avatar}
{
    setAlignment(Qt::AlignCenter); // 默认居中
}

void AvatarLabel::paintEvent(QPaintEvent *event)
{
    Q_UNUSED(event);

    QPainter painter(this);
    painter.setRenderHint(QPainter::Antialiasing);

    if (m_pixmap.isNull())
    {
        // 如果没有图片，绘制一个默认背景或圆形边框
        painter.setPen(Qt::NoPen);
        painter.setBrush(Qt::gray); // 默认背景颜色
        painter.drawEllipse(rect());
        return;
    }

    // 1. 绘制圆形图像
    QPixmap scaledPixmap = m_pixmap.scaled(size(), Qt::KeepAspectRatioByExpanding, Qt::SmoothTransformation);
    QRect pixmapRect = scaledPixmap.rect();

    int x = (width() - pixmapRect.width()) / 2;
    int y = (height() - pixmapRect.height()) / 2;
    QRect drawRect(x, y, pixmapRect.width(), pixmapRect.height());

    QPainterPath path;
    path.addEllipse(rect());

    painter.setClipPath(path);
    painter.drawPixmap(drawRect, scaledPixmap);

    // 2. 绘制圆形边框（替代原来的 setStyleSheet）
    QPen pen;
    pen.setWidth(2);      // 边框宽度
    pen.setColor("#ccc"); // 边框颜色
    painter.setPen(pen);
    painter.setBrush(Qt::NoBrush);
    painter.drawEllipse(rect().adjusted(1, 1, -1, -1)); // 留出边框宽度空间
}

void AvatarLabel::setPixmap(const QPixmap &pixmap)
{
    m_pixmap = pixmap;
    update(); // 触发重绘
}
